package com.hontech.dapapp.ui

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.hontech.dapapp.utils.hideSoftKey
import kotlinx.coroutines.CompletableDeferred

open class BaseActivity : AppCompatActivity() {


    companion object {
        lateinit var INSTANCE: BaseActivity
            private set

        fun parentView(): View {
            return INSTANCE.window.decorView
        }
    }

    private var permissionFuture: CompletableDeferred<Boolean>? = null


    @SuppressLint("MissingSuperCall")
    override fun onConfigurationChanged(newConfig: Configuration) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        INSTANCE = this
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            hideSoftKey(this)
        }
        return super.dispatchTouchEvent(ev)
    }

    fun hideButton() {
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_IMMERSIVE
    }

    fun replaceFragment(id: Int, fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(id, fragment)
            .commit()
    }

    fun replaceFragment2(id: Int, fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(id, fragment)
            .addToBackStack(null)
            .commit()
    }

    suspend fun requestPermission(permission: String) {
        permissionFuture = CompletableDeferred()
        requestPermissions(arrayOf(permission), 0)
        val ret = permissionFuture!!.await()
        if (!ret) {
            throw IllegalStateException("没有授权读写访问")
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty()) {
            permissionFuture?.complete(grantResults[0] == PackageManager.PERMISSION_GRANTED)
        }
    }
}